package fr.utbm.gi.in56.ads;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.utbm.gi.in56.error.ErrorType;

/**
 * Servlet implementation class SearchBuyAdServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet( "/SearchBuyAdServlet" )
public class SearchBuyAdServlet extends AdServlet
{
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see SearchAdServlet#SearchAdServlet()
	 */
	public SearchBuyAdServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		
		int idBrand 		= Integer.parseInt( request.getParameter( "brand" ) );
		int idModel 		= ( request.getParameter( "model" ) == null ) ? 0 : 
			Integer.parseInt( request.getParameter( "model" ) );
		int vehicleYear 	= Integer.parseInt( request.getParameter( "vehicle_year" ) );
		int idEnergy 		= Integer.parseInt( request.getParameter( "energy" ) );
		int automatic 		= Integer.parseInt( request.getParameter( "is_automatic" ) );	
		int[] kmNb			= new int[1];
		int[] price			= new int[1];
		
		// Get a representative value for the minimum number of kilometers
		if( ! handleParameter( request, "km_nb", kmNb, response, ErrorType.FIELD_NAN ) )
		{
			return;
		}
	
		// Get a representative value for the minimum price
		if( ! handleParameter( request, "price", price, response, ErrorType.FIELD_NAN ) )
		{
			return;
		}
		
		ErrorType result = forwardEnergyAndCarLists( request, response );
		if ( result != ErrorType.NONE )
		{
			request.setAttribute( "error", result ); //$NON-NLS-1$
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp"); //$NON-NLS-1$
			rd.forward( request, response );
			
			return;
		}
		
		AdsManager adsMg = new AdsManager( getConnection() );
		List< AdBuy > adBuyList = adsMg.getBuyAds( idBrand, idModel,
				automatic, price[0], vehicleYear, kmNb[0], idEnergy, 0,
				0, false, AdState.OPENED.ordinal(), -1, 0,
				"", "" );
		
		request.setAttribute( "adBuyList", adBuyList ); //$NON-NLS-1$
		
		forwardParameters( request );
		
		RequestDispatcher rd = request.getRequestDispatcher("searchBuyAd.jsp"); //$NON-NLS-1$
		rd.forward( request, response );
	}
	
	/**
	 * Sets the error as request attribute and forward to previous page.
	 * 
	 * @param _error the error
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void returnError( HttpServletRequest request,
			HttpServletResponse response, ErrorType _error ) throws ServletException, IOException
	{
		ErrorType result = forwardEnergyAndCarLists( request, response );
		if ( result != ErrorType.NONE )
		{
			request.setAttribute( "error", result ); //$NON-NLS-1$
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp"); //$NON-NLS-1$
			rd.forward( request, response );
		}
		else
		{
			forwardParameters( request );
			
			request.setAttribute( "searchAdError", _error ); //$NON-NLS-1$
			RequestDispatcher rd = request.getRequestDispatcher("searchBuyAd.jsp"); //$NON-NLS-1$
			rd.forward( request, response );
		}
	}
	
	/**
	 * Forward request parameters as attributes.
	 * 
	 * @param request the servlet request
	 */
	private void forwardParameters( HttpServletRequest request )
	{
		request.setAttribute( "brand", request.getParameter( "brand" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "model", request.getParameter( "model" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "vehicle_year", request.getParameter( "vehicle_year" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "km_nb", request.getParameter( "km_nb" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "energy", request.getParameter( "energy" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "is_automatic", request.getParameter( "is_automatic" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		request.setAttribute( "price", request.getParameter( "price" ) ); //$NON-NLS-1$ //$NON-NLS-2$
	}
	
	/**
	 * Sets the parameter to -1 if the parameter value is null,
	 * to the corresponding integer value if there is no format problem.
	 * 
	 * @param _request the servlet request
	 * @param _parameter the parameter to check
	 * @param _parameterValue the parameter to initialize
	 * @param _response the servlet response
	 * @param _errorToReturn the error to return
	 * @return <tt>true</tt> if there is no format exception
	 * @throws ServletException
	 * @throws IOException
	 */
	private boolean handleParameter( HttpServletRequest _request, String _parameter,
			int[] _parameterValue, HttpServletResponse _response, ErrorType _errorToReturn ) throws ServletException, IOException
	{
		if( _request.getParameter( _parameter ).isEmpty() )
		{
			_parameterValue[0] = -1;
			
			return true;
		}
		try
		{
			_parameterValue[0] = Integer.parseInt( _request.getParameter( _parameter ) );
			if( _parameterValue[0] < 0 )
			{
				returnError( _request, _response, _errorToReturn );
				return false;
			}
			
			return true;
		}
		catch (NumberFormatException e)
		{
			returnError( _request, _response, _errorToReturn );
			
			return false;
		}
	}
}
